<template>
  <div class="user-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>用户管理</h2>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入用户名或手机号搜索"
        clearable
        style="width: 300px;"
        @keyup.enter="loadUserData"
      >
        <template #append>
          <el-button type="primary" @click="loadUserData">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </template>
      </el-input>
      
      <el-button type="success" @click="openAddDialog">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%; margin-top: 16px;"
      v-loading="loading"
    >
      <el-table-column prop="index" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
      <el-table-column prop="nickname" label="昵称" min-width="120"></el-table-column>
      <el-table-column prop="realName" label="真实姓名" min-width="120"></el-table-column>
      <el-table-column prop="phone" label="手机号" min-width="130"></el-table-column>
      <el-table-column prop="source" label="来源" min-width="100"></el-table-column>
      <el-table-column prop="加达币" label="加达币" min-width="100" align="right"></el-table-column>
      <el-table-column prop="inviter" label="邀请人" min-width="120"></el-table-column>
      <el-table-column label="操作" min-width="250" align="center">
        <template #default="scope">
          <el-button 
            size="small" 
            type="primary" 
            @click="openEditDialog(scope.row)"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
          <el-button 
            size="small" 
            type="info" 
            @click="showConsumptionDetails(scope.row)"
          >
            消费明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
      />
    </div>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        size="default"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="formData.username" 
            placeholder="请输入用户名"
            :disabled="isEditMode"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="formData.nickname" 
            placeholder="请输入昵称"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input 
            v-model="formData.realName" 
            placeholder="请输入真实姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="formData.phone" 
            placeholder="请输入手机号"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-select 
            v-model="formData.source" 
            placeholder="请选择来源"
          >
            <el-option label="授权" value="授权"></el-option>
            <el-option label="注册" value="注册"></el-option>
            <el-option label="导入" value="导入"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加达币" prop="加达币">
          <el-input 
            v-model="formData.加达币" 
            placeholder="请输入加达币数量"
            type="number"
            min="0"
          ></el-input>
        </el-form-item>
        <el-form-item label="邀请人" prop="inviter">
          <el-input 
            v-model="formData.inviter" 
            placeholder="请输入邀请人用户名"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue';

// 状态管理
const tableData = ref([]);
const loading = ref(false);
const searchQuery = ref('');
const dialogVisible = ref(false);
const dialogTitle = ref('新增用户');
const isEditMode = ref(false);
const userFormRef = ref(null);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表单数据
const formData = reactive({
  index: '',
  username: '',
  nickname: '',
  realName: '',
  phone: '',
  source: '',
  加达币: '',
  inviter: ''
});

// 表单验证规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请选择来源', trigger: 'change' }
  ],
  加达币: [
    { required: true, message: '请输入加达币数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '加达币数量不能为负数', trigger: 'blur' }
  ]
});

// 页面加载时获取数据
onMounted(() => {
  loadUserData();
});

// 加载用户数据
const loadUserData = async () => {
  loading.value = true;
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 800));
    
    // 模拟数据 - 实际项目中应从API获取
    const mockData = Array.from({ length: 20 }, (_, i) => ({
      index: (pagination.currentPage - 1) * pagination.pageSize + i + 1,
      username: `user${i + 1}`,
      nickname: `昵称${i + 1}`,
      realName: `真实姓名${i + 1}`,
      phone: `138${1000000 + i}`,
      source: ['授权', '注册', '导入', '其他'][Math.floor(Math.random() * 4)],
      加达币: Math.floor(Math.random() * 1000).toString(),
      inviter: i > 5 ? `user${i - 5}` : ''
    }));
    
    // 处理搜索
    const filteredData = searchQuery.value 
      ? mockData.filter(item => 
          item.username.includes(searchQuery.value) || 
          item.phone.includes(searchQuery.value)
        )
      : mockData;
    
    // 处理分页
    const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
    const endIndex = startIndex + pagination.pageSize;
    
    tableData.value = filteredData.slice(startIndex, endIndex);
    pagination.total = filteredData.length;
  } catch (error) {
    ElMessage.error('加载数据失败，请重试');
    console.error('加载数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 打开新增对话框
const openAddDialog = () => {
  isEditMode.value = false;
  dialogTitle.value = '新增用户';
  // 重置表单
  Object.keys(formData).forEach(key => {
    formData[key] = '';
  });
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  isEditMode.value = true;
  dialogTitle.value = '编辑用户';
  // 复制行数据到表单
  Object.keys(formData).forEach(key => {
    formData[key] = row[key];
  });
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return;
  
  try {
    // 表单验证
    await userFormRef.value.validate();
    
    // 模拟API请求
    loading.value = true;
    await new Promise(resolve => setTimeout(resolve, 500));
    
    if (isEditMode.value) {
      // 编辑操作
      const index = tableData.value.findIndex(item => item.username === formData.username);
      if (index !== -1) {
        tableData.value.splice(index, 1, { ...formData });
      }
      ElMessage.success('用户信息更新成功');
    } else {
      // 新增操作
      const newUser = {
        ...formData,
        index: pagination.total + 1
      };
      tableData.value.unshift(newUser);
      pagination.total++;
      ElMessage.success('用户新增成功');
    }
    
    dialogVisible.value = false;
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error(isEditMode.value ? '更新失败，请重试' : '新增失败，请重试');
    }
  } finally {
    loading.value = false;
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户【${row.username}】吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true;
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 从表格中移除
      const index = tableData.value.findIndex(item => item.username === row.username);
      if (index !== -1) {
        tableData.value.splice(index, 1);
        pagination.total--;
      }
      
      ElMessage.success('删除成功');
    } catch (error) {
      ElMessage.error('删除失败，请重试');
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 取消删除
    ElMessage.info('已取消删除');
  });
};

// 查看消费明细
const showConsumptionDetails = (row) => {
  ElMessage.info(`查看用户【${row.username}】的消费明细`);
  // 实际项目中可打开新窗口或弹窗展示消费明细
};

// 分页相关方法
const handlePageSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadUserData();
};

const handleCurrentPageChange = (page) => {
  pagination.currentPage = page;
  loadUserData();
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}
</style>
